package com.cea.papyrus.diagram.usecase.editpart;

import java.util.Iterator;

import org.eclipse.draw2d.geometry.Rectangle;
import org.eclipse.gef.EditPart;
import org.eclipse.gef.GraphicalEditPart;
import org.eclipse.gef.commands.Command;
import org.eclipse.gef.commands.CompoundCommand;
import org.eclipse.gef.requests.ChangeBoundsRequest;
import org.eclipse.gef.requests.CreateRequest;

import com.cea.papyrus.core.commands.GraphNodeSetConstraintCommand;
import com.cea.papyrus.core.editpart.FeatureListFlowLayoutEditPolicy;
import com.cea.papyrus.core.editpart.GraphNodeEditPart;
import com.cea.papyrus.diagraminterchange2.di2.GraphNode;

/**
 * EditPolicy for the Figure used by ExtensionPointListEditPart.
 */
public class ExtensionPointListEditPolicy extends FeatureListFlowLayoutEditPolicy {

	/**
	 * Creates a new ExtensionPointListEditPolicy
	 * @param elementType the type of element ma,ipulated by the list
	 */
	public ExtensionPointListEditPolicy(Class elementType) {
		super(elementType);
	}
	
	/* (non-Javadoc)
	 * @see com.cea.papyrus.common.editpart.FeatureListFlowLayoutEditPolicy#createAddCommand(org.eclipse.gef.EditPart, org.eclipse.gef.EditPart)
	 */
	@Override
	protected Command createAddCommand(EditPart child, EditPart after) {
		CompoundCommand command=new CompoundCommand();
		command.add(super.createAddCommand(child, after));
		//to obtain parentEditpart
		GraphicalEditPart editpart=(GraphicalEditPart)child.getParent();
		Iterator itgraphChild= ((GraphNodeEditPart)editpart).getGraphNode().getSemanticChild().iterator();
		while( itgraphChild.hasNext()){
			GraphNode gn= (GraphNode)itgraphChild.next();
			Rectangle r= new Rectangle(gn.getPosition().x,gn.getPosition().y+15, gn.getSize().width,gn.getSize().height);
			GraphNodeSetConstraintCommand locationCommand = new GraphNodeSetConstraintCommand(gn,
					new ChangeBoundsRequest(),
					r);
			command.add(locationCommand);
		}
		return command;
	}
	
	/* (non-Javadoc)
	 * @see com.cea.papyrus.common.editpart.FeatureListFlowLayoutEditPolicy#getCreateCommand(org.eclipse.gef.requests.CreateRequest)
	 */
	@Override
	protected Command getCreateCommand(CreateRequest request) {
		CompoundCommand command=new CompoundCommand();
		command.add(super.getCreateCommand(request));
		//to obtain parentEditpart
		GraphicalEditPart editpart=(GraphicalEditPart)getHost().getParent();
		Iterator itgraphChild= ((GraphNodeEditPart)editpart).getGraphNode().getSemanticChild().iterator();
		while( itgraphChild.hasNext()){
			GraphNode gn= (GraphNode)itgraphChild.next();
			Rectangle r= new Rectangle(gn.getPosition().x,gn.getPosition().y+15, gn.getSize().width,gn.getSize().height);
			GraphNodeSetConstraintCommand locationCommand = new GraphNodeSetConstraintCommand(gn,
					new ChangeBoundsRequest(),
					r);
			command.add(locationCommand);
		}
		return command;
	}
}
